package ua.org.extjsbuilder.parser.scanner;

import ua.org.extjsbuilder.parser.IToken;
import ua.org.extjsbuilder.parser.ITokenScanner;
import ua.org.extjsbuilder.parser.JSParseException;
import ua.org.extjsbuilder.parser.runtime.UnparsedToken;

public class CodeBlocksScanner implements ITokenScanner {
	private int deep;
	private int lastOpen;
	
	public void init() {
		deep = 0;
	}

	public void scan(IToken token) {
		if(token instanceof UnparsedToken){
			seachForBrackets((UnparsedToken)token);
		}
	}
	
	private void seachForBrackets(UnparsedToken token) {
		char[] data = token.getData();
		for(int i=0;i<data.length;i++){
			switch(data[i]){
			case '{':
				deep++;
				lastOpen = token.getLine();
				break;
			case '}':
				if(deep<=0){
					throw new JSParseException("Wrong closing bracket",
							token.getLine());
				}
				deep--;
				break;	
			}
		}
	}

	public void finish() {
		if(deep>0){
			throw new JSParseException("Unclosed code block",lastOpen);
		}
	}
}